package com.daxia.ogmall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.ogmall.dao.TagDAO;
import com.daxia.ogmall.dto.TagDTO;
import com.daxia.ogmall.model.Tag;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.BeanMapper;

@Service
public class TagService {
	
	@Autowired
	private TagDAO tagDAO;
	
	public List<TagDTO> find(TagDTO query, Page page) {
		List<Tag> models = tagDAO.find(query, page);
		List<TagDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<TagDTO> findAll() {
		return this.find(new TagDTO(), null);
	}
	
	public List<TagDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new TagDTO(), page);
	}
	
	public Long create(TagDTO dto) {
		Tag model = new Tag();
		toModel(model, dto);
		return tagDAO.create(model);
	}
	
	public TagDTO load(Long id) {
	    Tag model = tagDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(TagDTO dto) {
		Tag model = tagDAO.load(dto.getId());
		toModel(model, dto);
		tagDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				tagDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public TagDTO findOne(TagDTO query) {
		Tag model = tagDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<TagDTO> toDTOs(List<Tag> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<TagDTO>(0);
		}
		List<TagDTO> dtos = new ArrayList<TagDTO>(models.size());
		for (Tag model : models) {
	        TagDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private TagDTO toDTO(Tag model) {
		if (model == null) {
			return null;
		}
		TagDTO dto = BeanMapper.map(model, TagDTO.class);
		
		return dto;
	}
	
	private void toModel(Tag model, TagDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<Tag> toModels(List<TagDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<Tag>(0);
		}
		List<Tag> models = new ArrayList<Tag>(dtos.size());
		for (TagDTO dto : dtos) {
	        Tag model = new Tag();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
